package com.uzai.console.service.wxqaddfriend.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.WxgroupMemberStatusEnum;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.wechatprivate.wxq.wxgroupmenber.WxGroupMemberQuery;
import com.uzai.console.dto.wechatwork.wxq.wxgroupmenber.WxWorkGroupMemberQuery;
import com.uzai.console.dto.wxqaddfriend.wxqaddfriendtask.WxqAddFriendTaskDto;
import com.uzai.console.entity.WxqAddFriendTask;
import com.uzai.console.entity.WxqAddFriendTaskAddInfo;
import com.uzai.console.entity.es.*;
import com.uzai.console.enums.WxqAddFriendTaskStatusEnum;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.DeviceWxworkInfoMapper;
import com.uzai.console.mapper.WxqAddFriendTaskAddInfoMapper;
import com.uzai.console.mapper.WxqAddFriendTaskMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.service.wechatprivate.WxGroupMemberService;
import com.uzai.console.service.wechatwork.WxWorkGroupMemberService;
import com.uzai.console.service.wechatwork.WxworkContactsService;
import com.uzai.console.service.wxqaddfriend.WxqAddFriendTaskSyncService;
import com.uzai.console.vo.wechatprivate.wxq.wxgroupmember.WxGroupMemberInfoVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroup.WxWorkGroupInfoVo;
import com.uzai.console.vo.wechatwork.wxq.wxgroupmember.WxWorkGroupMemberInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 清理僵尸粉任务
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class WxqAddFriendTaskSyncServiceImpl implements WxqAddFriendTaskSyncService {

    Logger logger = LoggerFactory.getLogger(WxqAddFriendTaskSyncServiceImpl.class);

    @Autowired
    private WxqAddFriendTaskMapper wxqAddFriendTaskMapper;
    @Autowired
    private WxqAddFriendTaskAddInfoMapper wxqAddFriendTaskAddInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceWxworkInfoMapper deviceWxworkInfoMapper;
    @Autowired
    private WxContactsService wxContactsService;
    @Autowired
    private WxworkContactsService wxworkContactsService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private WxGroupMemberService wxGroupMemberService;
    @Autowired
    private WxWorkGroupMemberService wxWorkGroupMemberService;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;

    /**
     * 后台异步添加个人微信机器人清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void addWxqAddFriendTaskByWechat(WxqAddFriendTaskDto wxqAddFriendTaskDto){

        //查询
        String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, wxqAddFriendTaskDto.getMerId());

        List<String> groupIdList = wxqAddFriendTaskDto.getGroupIdList();
        if(groupIdList != null && groupIdList.size() > 0){
            int now = DateUtil.getNowTime();
            for (String groupId : groupIdList) {
                //查询此群是否存在
                Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, groupId, null);
                EsWxContacts esWxContacts  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), EsWxContacts.class);
                if(esWxContacts == null){
                    continue;
                }

                //判断此群对应机器人是否已经有添加好友任务
                WxqAddFriendTask wxqAddFriendTask = wxqAddFriendTaskMapper.selectByDeviceUniqueId(esWxContacts.getDeviceUniqueId(), wxqAddFriendTaskDto.getMerId());
                if(wxqAddFriendTask == null){
                    //保存清粉任务
                    wxqAddFriendTask = new WxqAddFriendTask();
                    wxqAddFriendTask.setId(IdWorker.getId());
                    wxqAddFriendTask.setMerId(wxqAddFriendTaskDto.getMerId());
                    wxqAddFriendTask.setName(wxqAddFriendTaskDto.getName());
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.INIT.getId());
                    wxqAddFriendTask.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                    wxqAddFriendTask.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                    wxqAddFriendTask.setNickExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getNickExcludeList())));
                    wxqAddFriendTask.setWxidExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getWxidExcludeList())));
                    wxqAddFriendTask.setLimitBlacklistPri(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()));
                    wxqAddFriendTask.setLimitBlacklistPub(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()));
                    wxqAddFriendTask.setAddDayMin(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMin()));
                    wxqAddFriendTask.setAddDayMax(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMax()));
                    wxqAddFriendTask.setAddDayLimit(0);
                    wxqAddFriendTask.setRateMin(Tools.getInteger(wxqAddFriendTaskDto.getRateMin()));
                    wxqAddFriendTask.setRateMax(Tools.getInteger(wxqAddFriendTaskDto.getRateMax()));
                    wxqAddFriendTask.setLimitTimeStart(wxqAddFriendTaskDto.getLimitTimeStart());
                    wxqAddFriendTask.setLimitTimeEnd(wxqAddFriendTaskDto.getLimitTimeEnd());
                    wxqAddFriendTask.setVerifyMsg(wxqAddFriendTaskDto.getVerifyMsg());
                    wxqAddFriendTask.setTotalNum(0);
                    wxqAddFriendTask.setAddNum(0);
                    wxqAddFriendTask.setAddTime(0);
                    wxqAddFriendTask.setAddDayNum(0);
                    wxqAddFriendTask.setCreateTime(now);
                    wxqAddFriendTask.setUpdateTime(now);
                    wxqAddFriendTaskMapper.insert(wxqAddFriendTask);
                }else{
                    //如果状态为未初始化，防止总数不正确，则此时不让添加（多线程并发进行初始化）
                    if(wxqAddFriendTask.getStatus().intValue() == WxqAddFriendTaskStatusEnum.INIT.getId().intValue()){
                        continue;
                    }else{ //其他状态，将此任务修改成初始化，封装添加好友数据
                        wxqAddFriendTask.setName(wxqAddFriendTaskDto.getName());
                        wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.INIT.getId());
                        wxqAddFriendTask.setNickExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getNickExcludeList())));
                        wxqAddFriendTask.setWxidExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getWxidExcludeList())));
                        wxqAddFriendTask.setLimitBlacklistPri(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()));
                        wxqAddFriendTask.setLimitBlacklistPub(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()));
                        wxqAddFriendTask.setAddDayMin(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMin()));
                        wxqAddFriendTask.setAddDayMax(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMax()));
                        wxqAddFriendTask.setRateMin(Tools.getInteger(wxqAddFriendTaskDto.getRateMin()));
                        wxqAddFriendTask.setRateMax(Tools.getInteger(wxqAddFriendTaskDto.getRateMax()));
                        wxqAddFriendTask.setLimitTimeStart(wxqAddFriendTaskDto.getLimitTimeStart());
                        wxqAddFriendTask.setLimitTimeEnd(wxqAddFriendTaskDto.getLimitTimeEnd());
                        wxqAddFriendTask.setVerifyMsg(wxqAddFriendTaskDto.getVerifyMsg());
                        wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
                    }
                }

                //手动选择群成员wxid添加好友
                if(wxqAddFriendTaskDto.getMemberIdList() != null && wxqAddFriendTaskDto.getMemberIdList().size() > 0){
                    //批量保存文件对象
                    List<WxqAddFriendTaskAddInfo> wxqAddFriendTaskAddInfoList = new ArrayList<>();
                    //添加好友总数量
                    int totalNumber = 0;
                    for (String memberId : wxqAddFriendTaskDto.getMemberIdList()) {
                        //查找该成员
                        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_GROUP_MEMBER, wxqAddFriendTaskDto.getMerId());
                        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_group_member, memberId, null);
                        EsWxGroupMember esWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWxGroupMember.class);
                        if(esWxGroupMember == null){
                            continue;
                        }

                        //判断是否排除昵称关键词
                        List<String> nickExcludeList = wxqAddFriendTaskDto.getNickExcludeList();
                        if(nickExcludeList != null && nickExcludeList.size() > 0){
                            boolean match = nickExcludeList.stream().anyMatch(item -> Tools.getStr(esWxGroupMember.getNick()).contains(item));
                            if (match) {
                                continue;
                            }
                        }

                        //判断是否排除wxid关键词
                        List<String> wxidExcludeList = wxqAddFriendTaskDto.getWxidExcludeList();
                        if(wxidExcludeList != null && wxidExcludeList.size() > 0){
                            boolean match = wxidExcludeList.stream().anyMatch(item -> item.equals(esWxGroupMember.getWxid()));
                            if (match) {
                                continue;
                            }
                        }

                        //是否私有黑名单过滤不添加
                        if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()) == 1){
                            //查询是否已经在黑名单当中
                            //id为merId_groupWxid_wxid
                            String blicklitPriId = wxqAddFriendTaskDto.getMerId() + "_" + esWxContacts.getWxid() + "_" + esWxGroupMember.getWxid();
                            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, blicklitPriId, null);
                            WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
                            if(wxqBlacklistPrv != null){
                                continue;
                            }
                        }

                        //是否全网黑名单过滤不添加
                        if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()) == 1){
                            //查询是否已经在黑名单当中
                            //id为成员wxid
                            String blicklitPubId = esWxGroupMember.getWxid();
                            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, blicklitPubId, null);
                            WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
                            if(wxqBlacklistPub != null){
                                continue;
                            }
                        }

                        //查询是否已经存在,存在则不需要添加
                        WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectByDeviceUniqueIdAndWxid(esWxContacts.getDeviceUniqueId(), esWxGroupMember.getWxid());
                        if(wxqAddFriendTaskAddInfo != null){
                            continue;
                        }

                        wxqAddFriendTaskAddInfo = new WxqAddFriendTaskAddInfo();
                        wxqAddFriendTaskAddInfo.setId(IdWorker.getId());
                        wxqAddFriendTaskAddInfo.setMerId(wxqAddFriendTaskDto.getMerId());
                        wxqAddFriendTaskAddInfo.setTaskId(wxqAddFriendTask.getId());
                        wxqAddFriendTaskAddInfo.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                        wxqAddFriendTaskAddInfo.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                        wxqAddFriendTaskAddInfo.setWxid(esWxGroupMember.getWxid());
                        wxqAddFriendTaskAddInfo.setNick(esWxGroupMember.getNick());
                        wxqAddFriendTaskAddInfo.setRemark(esWxGroupMember.getRemark());
                        wxqAddFriendTaskAddInfo.setHimg(esWxGroupMember.getHimg());
                        wxqAddFriendTaskAddInfo.setGroupWxid(esWxContacts.getWxid());
                        wxqAddFriendTaskAddInfo.setGroupNick(esWxContacts.getNick());
                        wxqAddFriendTaskAddInfo.setGroupRemark(esWxContacts.getRemark());
                        wxqAddFriendTaskAddInfo.setCreateTime(now);
                        wxqAddFriendTaskAddInfo.setUpdateTime(now);
                        wxqAddFriendTaskAddInfoList.add(wxqAddFriendTaskAddInfo);
                    }

                    //最后将所有记录，批量处理
                    if(wxqAddFriendTaskAddInfoList.size() > 0){
                        //去重复
                        wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                        //累加总数
                        totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                        //批量保存清理僵尸粉发送明细
                        wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                        //清空本次导出的数据列表
                        wxqAddFriendTaskAddInfoList.clear();
                    }

                    //将任务状态修改成进行中
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.ADDING.getId());
                    wxqAddFriendTask.setTotalNum(wxqAddFriendTask.getTotalNum() + totalNumber);
                    wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);

                }else{ //全部群成员添加好友申请
                    //批量保存文件对象(100条一次)
                    List<WxqAddFriendTaskAddInfo> wxqAddFriendTaskAddInfoList = new ArrayList<>();
                    //添加好友总数量
                    int totalNumber = 0;
                    WxGroupMemberQuery wxGroupMemberQuery = new WxGroupMemberQuery();
                    wxGroupMemberQuery.setMerId(wxqAddFriendTaskDto.getMerId());
                    wxGroupMemberQuery.setGroupId(groupId);
                    wxGroupMemberQuery.setStatus(WxgroupMemberStatusEnum.NORMAL.getValue()); //在群的
                    //执行分页查询对象
                    wxGroupMemberQuery.setSize(10);
                    int currentPage = 1;
                    wxGroupMemberQuery.setCurrent(currentPage);
                    Page<WxGroupMemberInfoVo> wxGroupMemberList = wxGroupMemberService.findWxGroupMemberList(wxGroupMemberQuery, false);
                    while(wxGroupMemberList != null && wxGroupMemberList.getRecords() != null && wxGroupMemberList.getRecords().size() > 0){
                        for(WxGroupMemberInfoVo wxGroupMemberInfoVo : wxGroupMemberList.getRecords()){

                            //判断是否排除昵称关键词
                            List<String> nickExcludeList = wxqAddFriendTaskDto.getNickExcludeList();
                            if(nickExcludeList != null && nickExcludeList.size() > 0){
                                boolean match = nickExcludeList.stream().anyMatch(item -> Tools.getStr(wxGroupMemberInfoVo.getNick()).contains(item));
                                if (match) {
                                    continue;
                                }
                            }

                            //判断是否排除wxid关键词
                            List<String> wxidExcludeList = wxqAddFriendTaskDto.getWxidExcludeList();
                            if(wxidExcludeList != null && wxidExcludeList.size() > 0){
                                boolean match = wxidExcludeList.stream().anyMatch(item -> item.equals(wxGroupMemberInfoVo.getWxid()));
                                if (match) {
                                    continue;
                                }
                            }

                            //是否私有黑名单过滤不添加
                            if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()) == 1){
                                //查询是否已经在黑名单当中
                                //id为merId_groupWxid_wxid
                                String blicklitPriId = wxqAddFriendTaskDto.getMerId() + "_" + esWxContacts.getWxid() + "_" + wxGroupMemberInfoVo.getWxid();
                                Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PRV, blicklitPriId, null);
                                WxqBlacklistPrv wxqBlacklistPrv  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqBlacklistPrv.class);
                                if(wxqBlacklistPrv != null){
                                    continue;
                                }
                            }

                            //是否全网黑名单过滤不添加
                            if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()) == 1){
                                //查询是否已经在黑名单当中
                                //id为成员wxid
                                String blicklitPubId = wxGroupMemberInfoVo.getWxid();
                                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_BLACKLIST_PUB, blicklitPubId, null);
                                WxqBlacklistPub wxqBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqBlacklistPub.class);
                                if(wxqBlacklistPub != null){
                                    continue;
                                }
                            }

                            //查询是否已经存在,存在则不需要添加
                            WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectByDeviceUniqueIdAndWxid(esWxContacts.getDeviceUniqueId(), wxGroupMemberInfoVo.getWxid());
                            if(wxqAddFriendTaskAddInfo != null){
                                continue;
                            }

                            wxqAddFriendTaskAddInfo = new WxqAddFriendTaskAddInfo();
                            wxqAddFriendTaskAddInfo.setId(IdWorker.getId());
                            wxqAddFriendTaskAddInfo.setMerId(wxqAddFriendTaskDto.getMerId());
                            wxqAddFriendTaskAddInfo.setTaskId(wxqAddFriendTask.getId());
                            wxqAddFriendTaskAddInfo.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                            wxqAddFriendTaskAddInfo.setDeviceUniqueId(esWxContacts.getDeviceUniqueId());
                            wxqAddFriendTaskAddInfo.setWxid(wxGroupMemberInfoVo.getWxid());
                            wxqAddFriendTaskAddInfo.setNick(wxGroupMemberInfoVo.getNick());
                            wxqAddFriendTaskAddInfo.setRemark(wxGroupMemberInfoVo.getRemark());
                            wxqAddFriendTaskAddInfo.setHimg(wxGroupMemberInfoVo.getHimg());
                            wxqAddFriendTaskAddInfo.setGroupWxid(esWxContacts.getWxid());
                            wxqAddFriendTaskAddInfo.setGroupNick(esWxContacts.getNick());
                            wxqAddFriendTaskAddInfo.setGroupRemark(esWxContacts.getRemark());
                            wxqAddFriendTaskAddInfo.setCreateTime(now);
                            wxqAddFriendTaskAddInfo.setUpdateTime(now);
                            wxqAddFriendTaskAddInfoList.add(wxqAddFriendTaskAddInfo);
                            //判断条数，如果条数大于100条，批量处理
                            if(wxqAddFriendTaskAddInfoList.size() >= 50){
                                //去重复
                                wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                //累加总数
                                totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                                //批量保存清理僵尸粉发送明细
                                wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                                //清空数据列表
                                wxqAddFriendTaskAddInfoList.clear();
                            }
                        }

                        //循环查询下一页
                        currentPage ++ ;
                        wxGroupMemberQuery.setCurrent(currentPage);
                        wxGroupMemberList = wxGroupMemberService.findWxGroupMemberList(wxGroupMemberQuery, false);
                    }

                    //最后将剩余不足100条的记录，批量处理
                    if(wxqAddFriendTaskAddInfoList.size() > 0){
                        //去重复
                        wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                        //累加总数
                        totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                        //批量保存清理僵尸粉发送明细
                        wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                        //清空本次导出的数据列表
                        wxqAddFriendTaskAddInfoList.clear();
                    }

                    //将任务状态修改成进行中
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.ADDING.getId());
                    wxqAddFriendTask.setTotalNum(wxqAddFriendTask.getTotalNum() + totalNumber);
                    wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
                }
            }
        }
    }

    /**
     * 后台异步添加企业微信机器人添加好友任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param wxqAddFriendTaskDto
     * @return null
     */
    @Async("taskExecutor")
    public void addWxqAddFriendTaskByWxwork(WxqAddFriendTaskDto wxqAddFriendTaskDto){

        //查询
        String uzai_workwx_group_info = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_INFO, wxqAddFriendTaskDto.getMerId());

        List<String> groupIdList = wxqAddFriendTaskDto.getGroupIdList();
        if(groupIdList != null && groupIdList.size() > 0){

            int now = DateUtil.getNowTime();

            for (String groupId : groupIdList) {

                //查询此群是否存在
                Map<String,Object> dataMp = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_info, groupId, null);
                WxWorkGroupInfoVo wxWorkGroupInfoVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), WxWorkGroupInfoVo.class);
                if(wxWorkGroupInfoVo == null){
                    continue;
                }

                //判断此群对应机器人是否已经有添加好友任务
                WxqAddFriendTask wxqAddFriendTask = wxqAddFriendTaskMapper.selectByDeviceUniqueId(wxWorkGroupInfoVo.getDeviceUniqueId(), wxqAddFriendTaskDto.getMerId());
                if(wxqAddFriendTask == null){
                    //保存清粉任务
                    wxqAddFriendTask = new WxqAddFriendTask();
                    wxqAddFriendTask.setId(IdWorker.getId());
                    wxqAddFriendTask.setMerId(wxqAddFriendTaskDto.getMerId());
                    wxqAddFriendTask.setName(wxqAddFriendTaskDto.getName());
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.INIT.getId());
                    wxqAddFriendTask.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                    wxqAddFriendTask.setDeviceUniqueId(wxWorkGroupInfoVo.getDeviceUniqueId());
                    wxqAddFriendTask.setNickExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getNickExcludeList())));
                    wxqAddFriendTask.setWxidExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getWxidExcludeList())));
                    wxqAddFriendTask.setLimitBlacklistPri(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()));
                    wxqAddFriendTask.setLimitBlacklistPub(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()));
                    wxqAddFriendTask.setAddDayMin(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMin()));
                    wxqAddFriendTask.setAddDayMax(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMax()));
                    wxqAddFriendTask.setAddDayLimit(0);
                    wxqAddFriendTask.setRateMin(Tools.getInteger(wxqAddFriendTaskDto.getRateMin()));
                    wxqAddFriendTask.setRateMax(Tools.getInteger(wxqAddFriendTaskDto.getRateMax()));
                    wxqAddFriendTask.setLimitTimeStart(wxqAddFriendTaskDto.getLimitTimeStart());
                    wxqAddFriendTask.setLimitTimeEnd(wxqAddFriendTaskDto.getLimitTimeEnd());
                    wxqAddFriendTask.setVerifyMsg(wxqAddFriendTaskDto.getVerifyMsg());
                    wxqAddFriendTask.setTotalNum(0);
                    wxqAddFriendTask.setAddNum(0);
                    wxqAddFriendTask.setAddTime(0);
                    wxqAddFriendTask.setAddDayNum(0);
                    wxqAddFriendTask.setCreateTime(now);
                    wxqAddFriendTask.setUpdateTime(now);
                    wxqAddFriendTaskMapper.insert(wxqAddFriendTask);
                }else{
                    //如果状态为未初始化，防止总数不正确，则此时不让添加（多线程并发进行初始化）
                    if(wxqAddFriendTask.getStatus().intValue() == WxqAddFriendTaskStatusEnum.INIT.getId().intValue()){
                        continue;
                    }else{
                        wxqAddFriendTask.setName(wxqAddFriendTaskDto.getName());
                        wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.INIT.getId());
                        wxqAddFriendTask.setNickExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getNickExcludeList())));
                        wxqAddFriendTask.setWxidExclude(Tools.getStrNull(JSONObject.toJSONString(wxqAddFriendTaskDto.getWxidExcludeList())));
                        wxqAddFriendTask.setLimitBlacklistPri(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()));
                        wxqAddFriendTask.setLimitBlacklistPub(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()));
                        wxqAddFriendTask.setAddDayMin(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMin()));
                        wxqAddFriendTask.setAddDayMax(Tools.getInteger(wxqAddFriendTaskDto.getAddDayMax()));
                        wxqAddFriendTask.setRateMin(Tools.getInteger(wxqAddFriendTaskDto.getRateMin()));
                        wxqAddFriendTask.setRateMax(Tools.getInteger(wxqAddFriendTaskDto.getRateMax()));
                        wxqAddFriendTask.setLimitTimeStart(wxqAddFriendTaskDto.getLimitTimeStart());
                        wxqAddFriendTask.setLimitTimeEnd(wxqAddFriendTaskDto.getLimitTimeEnd());
                        wxqAddFriendTask.setVerifyMsg(wxqAddFriendTaskDto.getVerifyMsg());
                        wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
                    }
                }

                //手动选择群成员wxid添加好友
                if(wxqAddFriendTaskDto.getMemberIdList() != null && wxqAddFriendTaskDto.getMemberIdList().size() > 0){
                    //批量保存文件对象
                    List<WxqAddFriendTaskAddInfo> wxqAddFriendTaskAddInfoList = new ArrayList<>();
                    //添加好友总数量
                    int totalNumber = 0;
                    for (String memberId : wxqAddFriendTaskDto.getMemberIdList()) {
                        //查找该成员
                        String uzai_workwx_group_member = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WORKWX_GROUP_MEMBER, wxqAddFriendTaskDto.getMerId());
                        String uzai_wx_group_member = merchantService.getMechantOtherEsIndexName(uzai_workwx_group_member, wxqAddFriendTaskDto.getMerId());
                        Map<String,Object> dataMp_member = elasticsearchUtilGroupMsg.searchDataById(uzai_workwx_group_member, memberId, null);
                        EsWorkWxGroupMember esWorkWxGroupMember  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp_member)), EsWorkWxGroupMember.class);
                        if(esWorkWxGroupMember == null){
                           continue;
                        }

                        //判断是否排除昵称关键词
                        List<String> nickExcludeList = wxqAddFriendTaskDto.getNickExcludeList();
                        if(nickExcludeList != null && nickExcludeList.size() > 0){
                            boolean match = nickExcludeList.stream().anyMatch(item -> Tools.getStr(esWorkWxGroupMember.getNick()).contains(item));
                            if (match) {
                                continue;
                            }
                        }

                        //判断是否排除wxid关键词
                        List<String> wxidExcludeList = wxqAddFriendTaskDto.getWxidExcludeList();
                        if(wxidExcludeList != null && wxidExcludeList.size() > 0){
                            boolean match = wxidExcludeList.stream().anyMatch(item -> item.equals(esWorkWxGroupMember.getWxid()));
                            if (match) {
                                continue;
                            }
                        }

                        //是否私有黑名单过滤不添加
                        if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()) == 1){
                            //查询是否已经在黑名单当中
                            //id为merId_groupWxid_wxid
                            String blicklitPriId = wxqAddFriendTaskDto.getMerId() + "_" + wxWorkGroupInfoVo.getGroupId() + "_" + esWorkWxGroupMember.getWxid();
                            Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, blicklitPriId, null);
                            WxqWorkBlacklistPrv wxqWorkBlacklistPrv_old  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
                            if(wxqWorkBlacklistPrv_old != null){
                                continue;
                            }
                        }

                        //是否全网黑名单过滤不添加
                        if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()) == 1){
                            //查询是否已经在黑名单当中
                            //id为成员wxid
                            String blicklitPubId = esWorkWxGroupMember.getWxid();
                            Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, blicklitPubId, null);
                            WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
                            if(wxqWorkBlacklistPub != null){
                                continue;
                            }
                        }

                        //查询是否已经存在,存在则不需要添加
                        WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectByDeviceUniqueIdAndWxid(wxWorkGroupInfoVo.getDeviceUniqueId(), esWorkWxGroupMember.getWxid());
                        if(wxqAddFriendTaskAddInfo != null){
                            continue;
                        }

                        wxqAddFriendTaskAddInfo = new WxqAddFriendTaskAddInfo();
                        wxqAddFriendTaskAddInfo.setId(IdWorker.getId());
                        wxqAddFriendTaskAddInfo.setMerId(wxqAddFriendTaskDto.getMerId());
                        wxqAddFriendTaskAddInfo.setTaskId(wxqAddFriendTask.getId());
                        wxqAddFriendTaskAddInfo.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                        wxqAddFriendTaskAddInfo.setDeviceUniqueId(wxWorkGroupInfoVo.getDeviceUniqueId());
                        wxqAddFriendTaskAddInfo.setWxid(esWorkWxGroupMember.getWxid());
                        wxqAddFriendTaskAddInfo.setNick(esWorkWxGroupMember.getNick());
                        wxqAddFriendTaskAddInfo.setRemark(esWorkWxGroupMember.getNickRemark());
                        wxqAddFriendTaskAddInfo.setHimg(esWorkWxGroupMember.getHimg());
                        wxqAddFriendTaskAddInfo.setGroupWxid(wxWorkGroupInfoVo.getGroupId());
                        wxqAddFriendTaskAddInfo.setGroupNick(wxWorkGroupInfoVo.getNickName());
                        wxqAddFriendTaskAddInfo.setCreateTime(now);
                        wxqAddFriendTaskAddInfo.setUpdateTime(now);
                        wxqAddFriendTaskAddInfoList.add(wxqAddFriendTaskAddInfo);
                    }

                    //最后将所有记录，批量处理
                    if(wxqAddFriendTaskAddInfoList.size() > 0){
                        //去重复
                        wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                        //计算总数
                        totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                        //批量保存清理僵尸粉发送明细
                        wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                        //清空本次导出的数据列表
                        wxqAddFriendTaskAddInfoList.clear();
                    }

                    //将任务状态修改成进行中
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.ADDING.getId());
                    wxqAddFriendTask.setTotalNum(wxqAddFriendTask.getTotalNum() + totalNumber);
                    wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);

                }else{ //全部群成员添加好友申请
                    //批量保存文件对象(100条一次)
                    List<WxqAddFriendTaskAddInfo> wxqAddFriendTaskAddInfoList = new ArrayList<>();
                    //添加好友总数量
                    int totalNumber = 0;
                    WxWorkGroupMemberQuery wxWorkGroupMemberQuery = new WxWorkGroupMemberQuery();
                    wxWorkGroupMemberQuery.setMerId(wxqAddFriendTaskDto.getMerId());
                    wxWorkGroupMemberQuery.setGroupId(groupId);
                    wxWorkGroupMemberQuery.setStatus(WxgroupMemberStatusEnum.NORMAL.getValue()); //在群的
                    //执行分页查询对象
                    wxWorkGroupMemberQuery.setSize(10);
                    int currentPage = 1;
                    wxWorkGroupMemberQuery.setCurrent(currentPage);
                    Page<WxWorkGroupMemberInfoVo> wxWorkGroupMemberList = wxWorkGroupMemberService.findWxWorkGroupMemberList(wxWorkGroupMemberQuery, false);
                    while(wxWorkGroupMemberList != null && wxWorkGroupMemberList.getRecords() != null && wxWorkGroupMemberList.getRecords().size() > 0){
                        for(WxWorkGroupMemberInfoVo wxWorkGroupMemberInfoVo : wxWorkGroupMemberList.getRecords()){

                            //判断是否排除昵称关键词
                            List<String> nickExcludeList = wxqAddFriendTaskDto.getNickExcludeList();
                            if(nickExcludeList != null && nickExcludeList.size() > 0){
                                boolean match = nickExcludeList.stream().anyMatch(item -> Tools.getStr(wxWorkGroupMemberInfoVo.getNick()).contains(item));
                                if (match) {
                                    continue;
                                }
                            }

                            //判断是否排除wxid关键词
                            List<String> wxidExcludeList = wxqAddFriendTaskDto.getWxidExcludeList();
                            if(wxidExcludeList != null && wxidExcludeList.size() > 0){
                                boolean match = wxidExcludeList.stream().anyMatch(item -> item.equals(wxWorkGroupMemberInfoVo.getWxid()));
                                if (match) {
                                    continue;
                                }
                            }

                            //是否私有黑名单过滤不添加
                            if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPri()) == 1){
                                //查询是否已经在黑名单当中
                                //id为merId_groupWxid_wxid
                                String blicklitPriId = wxqAddFriendTaskDto.getMerId() + "_" + wxWorkGroupInfoVo.getGroupId() + "_" + wxWorkGroupMemberInfoVo.getWxid();
                                Map<String,Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PRV, blicklitPriId, null);
                                WxqWorkBlacklistPrv wxqWorkBlacklistPrv_old  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WxqWorkBlacklistPrv.class);
                                if(wxqWorkBlacklistPrv_old != null){
                                    continue;
                                }
                            }

                            //是否全网黑名单过滤不添加
                            if(Tools.getInteger(wxqAddFriendTaskDto.getLimitBlacklistPub()) == 1){
                                //查询是否已经在黑名单当中
                                //id为成员wxid
                                String blicklitPubId = wxWorkGroupMemberInfoVo.getWxid();
                                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WXQ_WORK_BLACKLIST_PUB, blicklitPubId, null);
                                WxqWorkBlacklistPub wxqWorkBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WxqWorkBlacklistPub.class);
                                if(wxqWorkBlacklistPub != null){
                                    continue;
                                }
                            }

                            //查询是否已经存在,存在则不需要添加
                            WxqAddFriendTaskAddInfo wxqAddFriendTaskAddInfo = wxqAddFriendTaskAddInfoMapper.selectByDeviceUniqueIdAndWxid(wxWorkGroupInfoVo.getDeviceUniqueId(), wxWorkGroupMemberInfoVo.getWxid());
                            if(wxqAddFriendTaskAddInfo != null){
                                continue;
                            }

                            wxqAddFriendTaskAddInfo = new WxqAddFriendTaskAddInfo();
                            wxqAddFriendTaskAddInfo.setId(IdWorker.getId());
                            wxqAddFriendTaskAddInfo.setMerId(wxqAddFriendTaskDto.getMerId());
                            wxqAddFriendTaskAddInfo.setTaskId(wxqAddFriendTask.getId());
                            wxqAddFriendTaskAddInfo.setDeviceType(wxqAddFriendTaskDto.getDeviceType());
                            wxqAddFriendTaskAddInfo.setDeviceUniqueId(wxWorkGroupInfoVo.getDeviceUniqueId());
                            wxqAddFriendTaskAddInfo.setWxid(wxWorkGroupMemberInfoVo.getWxid());
                            wxqAddFriendTaskAddInfo.setNick(wxWorkGroupMemberInfoVo.getNick());
                            wxqAddFriendTaskAddInfo.setRemark(wxWorkGroupMemberInfoVo.getNickRemark());
                            wxqAddFriendTaskAddInfo.setHimg(wxWorkGroupMemberInfoVo.getHimg());
                            wxqAddFriendTaskAddInfo.setGroupWxid(wxWorkGroupInfoVo.getGroupId());
                            wxqAddFriendTaskAddInfo.setGroupNick(wxWorkGroupInfoVo.getNickName());
                            wxqAddFriendTaskAddInfo.setCreateTime(now);
                            wxqAddFriendTaskAddInfo.setUpdateTime(now);
                            wxqAddFriendTaskAddInfoList.add(wxqAddFriendTaskAddInfo);
                            //判断条数，如果条数大于100条，批量处理
                            if(wxqAddFriendTaskAddInfoList.size() >= 50){
                                //去重复
                                wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                                //累加总数
                                totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                                //批量保存清理僵尸粉发送明细
                                wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                                //清空数据列表
                                wxqAddFriendTaskAddInfoList.clear();
                            }
                        }

                        //循环查询下一页
                        currentPage ++ ;
                        wxWorkGroupMemberQuery.setCurrent(currentPage);
                        wxWorkGroupMemberList = wxWorkGroupMemberService.findWxWorkGroupMemberList(wxWorkGroupMemberQuery, false);
                    }

                    //最后将剩余不足100条的记录，批量处理
                    if(wxqAddFriendTaskAddInfoList.size() > 0){
                        //去重复
                        wxqAddFriendTaskAddInfoList = wxqAddFriendTaskAddInfoList.stream().distinct().collect(Collectors.toList());
                        //累加总数
                        totalNumber = totalNumber + wxqAddFriendTaskAddInfoList.size();
                        //批量保存清理僵尸粉发送明细
                        wxqAddFriendTaskAddInfoMapper.batchAdd(wxqAddFriendTaskAddInfoList);
                        //清空本次导出的数据列表
                        wxqAddFriendTaskAddInfoList.clear();
                    }

                    //将任务状态修改成进行中
                    wxqAddFriendTask.setStatus(WxqAddFriendTaskStatusEnum.ADDING.getId());
                    wxqAddFriendTask.setTotalNum(wxqAddFriendTask.getTotalNum() + totalNumber);
                    wxqAddFriendTaskMapper.updateById(wxqAddFriendTask);
                }
            }
        }
    }


}
